{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 读/写 txt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "欢迎大家回到 Machine Learning Diary~👏\n",
    "今天这节课主要带大家熟悉一下 读read 和 写write text文件。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在熟悉txt之前，我先来介绍下 \"路径 path\" 这个概念。\n",
    "\n",
    "很简单，每个文件都有它归属的路径。比如我在桌面新建个python文件夹，那么它对应的路径是\"C:\\Users\\ZhangYi\\Desktop\\python\"，这个叫\"绝对路径\"，还有个\"相对路径\"，稍后讲。我继续在python文件夹里新建一个 python.txt 文本文件，那么它对应的绝对路径是\"C:\\Users\\ZhangYi\\Desktop\\python\\python.txt\"。\n",
    "\n",
    "如果要把这个路径写进python代码里，为了能使程序识别出来，在windows下的路径的斜杠是'/',linux下的路径斜杠是\"\\\\\\\\\"。\n",
    "\n",
    "好了，现在打开刚刚新建的python.txt，顶格在第一行写上\"皮一下很开心！\"，然后关掉。（不用写引号\"\"）\n",
    "\n",
    "打开jupyter notebook，运行下面的代码："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.chdir(\"C:/Users/ZhangYi/Desktop/python\") # 这里更换成你的python文件夹路径，记得更正斜杠'/'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在已经进入到python这个文件夹内，运行下面的代码尝试打开这个文件夹下的 python.txt 文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<_io.TextIOWrapper name='python.txt' mode='r' encoding='cp936'>\n"
     ]
    }
   ],
   "source": [
    "f = open('python.txt')  # 这里的'python.txt'就是相对路径\n",
    "print(f)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "跑出一行看不太懂的东西，跳过！我们接着来看这个txt文件夹内的东西，尝试读取这个文件，运行下面的代码："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "皮一下很开心！\n"
     ]
    }
   ],
   "source": [
    "a = f.read()\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "\n",
    "很好，这下终于跳出看得懂的内容了！这就是我们刚刚输入的文字。回到桌面，打开python.txt文件我们继续添加内容，然后保存，然后关掉。最后我的txt长下面这样："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 不要运行这个框\n",
    "\n",
    "皮一下很开心！\n",
    "I love three things in this world.\n",
    "Sun, moon and you.\n",
    "Sun for morning,\n",
    "moon for night,\n",
    "and you forever."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "按照上面的步骤，来运行下这个刚修改过的文件，运行下面的代码："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "皮一下很开心！\n",
      "I love three things in this world.\n",
      "Sun, moon and you. \n",
      "Sun for morning, \n",
      "moon for night, \n",
      "and you forever.\n"
     ]
    }
   ],
   "source": [
    "f = open('python.txt')\n",
    "a = f.read()\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "皮一下很开心！\n",
      "I love three things in this world.\n",
      "Sun, moon and you. \n",
      "Sun for morning, \n",
      "moon for night, \n",
      "and you forever.\n"
     ]
    }
   ],
   "source": [
    "f = open('python.txt')  # 这里的'python.txt'就是相对路径\n",
    "print(f.read())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "皮一下很开心！\n",
      "\n"
     ]
    }
   ],
   "source": [
    "f = open('python.txt')\n",
    "print(f.readline())     # 读取一行内容"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['皮一下很开心！\\n', 'I love three things in this world.\\n', 'Sun, moon and you. \\n', 'Sun for morning, \\n', 'moon for night, \\n', 'and you forever.']\n"
     ]
    }
   ],
   "source": [
    "f = open('python.txt')\n",
    "print(f.readlines())    # 读取每行内容，并且形成一个list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 最后，我们打开了文件，还需要关上\n",
    "# 运行下面的代码，将文件关闭\n",
    "\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "I/O operation on closed file.",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-35-1417de781596>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[1;31m# 此时你再尝试读文件时，就会报错了\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[1;31m# 尝试运行下面的代码\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0mf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mreadlines\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m: I/O operation on closed file."
     ]
    }
   ],
   "source": [
    "# 此时你再尝试读文件时，就会报错了\n",
    "# 尝试运行下面的代码\n",
    "f.readlines()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "按照上面的错误提示，表示已经关闭文件，不能再访问。\n",
    "\n",
    "接下来看如何写内容到 txt文件里去！运行下面这行代码，打开文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = open('python.txt', 'w')   # 括号内第二个参数'w'是write的缩写"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "此时你已经打开了这个txt文件，进行文字写入"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "12"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.write('我写的东西即将覆盖所有！')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "写完还不算完，必须关闭文件才能看见自己写的，运行下面代码关闭文件。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [],
   "source": [
    "a.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "好了，现在回到桌面，看看你的python.txt文件内的内容是什么吧！\n",
    "\n",
    "完整的demo如下，可以再运行一遍："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "words = 'I\\'m so proud of myself!\\nI\\'m so proud of Girls in AI!'\n",
    "f = open('python.txt','w')\n",
    "f.write(words)\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "是不是有点小惊喜，不用鼠标点击文件就能改动文件内容！"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 作业 "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在一个空的txt文件里，不用鼠标，只用python，写下你的2019新年愿望！\n",
    "\n",
    "欢迎在微博@Girls-In-AI @CodeWithZhangYi 来分享你的成果！👏\n",
    "\n",
    "好啦！今天的课程就到这里啦！我们下次见~"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
